<?php

namespace app\model;

use app\observer\AdminObserver;
use Shopwwi\LaravelCache\Cache;

/**
 * 管理员模型
 */
class AdminModel extends BaseModel
{

    protected $table = 'admin';


    /**
     * 获取管理员信息(缓存，不包含敏感信息)
     *
     * @param integer $admin_id 管理员id
     * @param boolean $is_update 是否更新缓存
     * @return void
     */
    public function getDetail($admin_id = 0, $is_update = false)
    {
        if (empty($admin_id)) return [];

        $admin = Cache::get('admin_info_' . $admin_id);

        if (empty($admin) || $is_update) {

            $admin = $this->where("id", $admin_id)->first();
            if (empty($admin)){
                Cache::forget('admin_info_' . $admin_id);
                return [];
            }

            $admin = $admin->toArray();
            unset($admin['password']);

            //缓存30天
            Cache::put('admin_info_' . $admin_id, $admin, 86400 * 30);
        }

        return $admin;
    }

    //获取管理员所有菜单ids
    public function getRulesIds($admin_id)
    {
        //获取缓存
        $ids = Cache::tags('admin_rules')->get('admin_rules_ids_' . $admin_id);

        if (empty($ids)) {

            //获取角色
            $roles_ids = $this->where("id", $admin_id)->value('roles');

            if (empty($roles_ids)) return [];

            $rules_list = AdminRolesModel::whereIn("id", explode(",", trim($roles_ids, ",")))->pluck("rules");
            $ids = [];
            foreach ($rules_list as $k => $v) {
                $ids = array_merge($ids, explode(",", $v));
            }
            //清除数组空内容，清除数组重复内容
            $ids = array_filter(array_unique($ids));

            //添加缓存
            Cache::tags('admin_rules')->put('admin_rules_ids_' . $admin_id, $ids, 86400 * 30);
        }
        return $ids;
    }
}
